using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;

namespace Jandaya.Framework.Application
{
	public class Configuration
	{
		private const string CONFIG_FILENAME = "Jandaya.exe.config";
		private const string ERR_FILE_NOT_FOUND = "O arquivo {0} não pôde ser encontrado!";
		private const string ERR_CONFIG_SESSION_NOT_FOUND = "A sessão de configuração do arquivo " + CONFIG_FILENAME + " não foi encontrada.";
		
		public Configuration()
		{
		}

		private bool _ConfigLoaded = false;
		public bool ConfigLoaded{ get {return _ConfigLoaded; }}
		
		private DatabaseInfo _DBInfo = null;
		public DatabaseInfo DBInfo{ 
			get{
				if(_DBInfo == null){
					_DBInfo = new DatabaseInfo();
				}
				return _DBInfo;
			}			
		}
		
		
		public bool Save(){							
			System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);							
			config.AppSettings.Settings.Remove("db.alias");
			config.AppSettings.Settings.Remove("db.host");
			config.AppSettings.Settings.Remove("db.database");
			config.AppSettings.Settings.Remove("db.username");
			config.AppSettings.Settings.Remove("db.password");
			
			config.AppSettings.Settings.Add("db.alias", DBInfo.ConnectionName);
			config.AppSettings.Settings.Add("db.host", DBInfo.HostName);
			config.AppSettings.Settings.Add("db.database", DBInfo.Database);
			config.AppSettings.Settings.Add("db.username", DBInfo.UserName);
			config.AppSettings.Settings.Add("db.password", DBInfo.Password);		
			
			config.Save(ConfigurationSaveMode.Modified);	
			ConfigurationManager.RefreshSection("appSettings");
			
			return true;	
		}
		
		
		public bool LoadConfiguration(){
			if (!File.Exists(CONFIG_FILENAME))
				throw new FileNotFoundException(string.Format(ERR_FILE_NOT_FOUND, CONFIG_FILENAME));
			
			if (!ConfigurationManager.AppSettings.HasKeys())
				throw new ConfigurationErrorsException(ERR_CONFIG_SESSION_NOT_FOUND);
			
			ConfigurationManager.RefreshSection("appSettings");
			this.DBInfo.ConnectionName = ConfigurationManager.AppSettings["db.alias"].ToString();
			this.DBInfo.HostName = ConfigurationManager.AppSettings["db.host"].ToString();
			this.DBInfo.Database = ConfigurationManager.AppSettings["db.database"];
			this.DBInfo.UserName = ConfigurationManager.AppSettings["db.username"];
			this.DBInfo.Password = ConfigurationManager.AppSettings["db.password"];		
			
			_ConfigLoaded = true;			
			return _ConfigLoaded;
		}	
	}
}

